import React from 'react'
import { renderToString, renderToNodeStream } from 'react-dom/server'
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'
import { StaticRouter } from 'react-router-dom'
import reducers from '../src/reducer'
// 注意 csshook 要放到引入 App 之前
import csshook from 'css-modules-require-hook/preset'
import assethook from 'asset-require-hook'

// 支持 图片
assethook({
  extensions: ['png'],
  publicPath: '/static/media/', // 前端图片打包到这里
  limit: 10000 // 这个值必须和前端 webpack 配置相同，否则如果前端的值大，可能后端引入的是图片路径，而前端其实编译成了 base64
})
// 引入 css,js 的路径
import staticPath from '../build/asset-manifest.json'

import App from '../src/app'

const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const mongoose = require('mongoose')
const path = require('path')
const app = express()

// test SSR
// function Cc() {
//   return <div>server react</div>
// }
// console.log(renderToString(<Cc />))

// init database
require('./model')
const Chat = mongoose.model('Chat')

// socket io
var server = require('http').createServer(app)
var io = require('socket.io')(server)

io.on('connection', function (socket) {
  console.log('user login')
  socket.on('sendmsg', function name(data) {
    // console.log('get msg', data)
    let { from, to, msg } = data
    const chatid = [from, to].sort().join('_')
    Chat.create({chatid, from, to, content: msg}, function (err, doc) {
      // console.log('doc', doc._doc)
      io.emit('recvmsg', Object.assign({}, doc._doc))
    })
  })
})

// middlewares
app.use(cookieParser())
app.use(bodyParser.json())

// router
const userRouter = require('./user')
app.use('/api', userRouter)

app.use(express.static(path.resolve(__dirname, '../build/')))
// 前端
app.use('*', function (req, res) {
  const store = createStore(reducers, compose(applyMiddleware(thunk)))
  let context = {}
  // 1. 使用 renderToString，字符串拼接，返回拼接后的字符串
  // const markup = renderToString(<Provider store={store} >
  //   <StaticRouter location={req.url} context={context}>
  //     <App />
  //   </StaticRouter>
  // </Provider>)

//   const pageHtml = `<!DOCTYPE html>
// <html lang="en">
//   <head>
//     <meta charset="utf-8">
//     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
//     <meta name="theme-color" content="#000000">
//     <link rel="stylesheet" href="/${staticPath['main.css']}">
//     <title>Boss App</title>
//   </head>
//   <body>
//     <noscript>
//       You need to enable JavaScript to run this app.
//     </noscript>
//     <div id="root">${markup}</div>
//     <script src="/${staticPath['main.js']}"></script>
//   </body>
// </html>`
  // 使用 renderToString 直接将拼接好的字符串返回
  // res.send(pageHtml)

  // 2. renderToNodeStream，一点点的 write
  res.write(`<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="stylesheet" href="/${staticPath['main.css']}">
    <title>Boss App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root">`)

  const markupStream = renderToNodeStream(<Provider store={store} >
    <StaticRouter location={req.url} context={context}>
      <App />
    </StaticRouter>
  </Provider>)

  markupStream.pipe(res, {end: false})
  markupStream.on('end', () => {
    res.write(`</div>
    <script src="/${staticPath['main.js']}"></script>
  </body>
</html>`)
    res.end()
  })

  // 单纯的前后端项目部署
  // res.sendFile(path.resolve(__dirname, '../build/index.html'))
})
// app.use('*', function (req, res) {
//   res.json({
//     code: 1,
//     msg: `can not find the path of ${req.path}`
//   })
// })

server.listen(9093, function () {
  console.log('app is runnint at port 9093')
})